/*
 * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited Licensed under the
 * Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
 * or agreed to in writing, software distributed under the License is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */

package com.test.webapp.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.test.clyq.entity.Users;

/**
 * Logs a principal out.
 * <p>
 * Polls a series of {@link LogoutHandler}s. The handlers should be specified
 * in the order they are required. Generally you will want to call logout
 * handlers <code>TokenBasedRememberMeServices</code> and
 * <code>SecurityContextLogoutHandler</code> (in that order).
 * </p>
 * <p>
 * After logout, the URL specified by {@link #logoutSuccessUrl} will be shown.
 * </p>
 * <p>
 * <b>Do not use this class directly.</b> Instead configure
 * <code>web.xml</code> to use the
 * {@link org.acegisecurity.util.FilterToBeanProxy}.
 * </p>
 * 
 * @author Ben Alex
 * @version $Id: PermissionManageCheckFilter.java,v 1.6 2008/12/08 10:59:51 lxl
 *          Exp $
 */
public class PermissionManageCheckFilter implements Filter {

	// ~ Static fields/initializers
	// =====================================================================================

	private static final Log log = LogFactory.getLog(PermissionManageCheckFilter.class);

	protected FilterConfig filterConfig;

	private static List<String> methodList = new ArrayList<String>();

	static {
		methodList.add("login");
		methodList.add("loginOut");
	}

	public PermissionManageCheckFilter() {
	}

	/**
	 * Not used. Use IoC container lifecycle methods instead.
	 */
	public void destroy() {
		this.filterConfig = null;

	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		// 获得url
		PermissionManageCheckFilter.log.info("[后台权限验证filter][开始过滤...]");

		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		HttpSession session = httpRequest.getSession();
		String method = request.getParameter("method");

		Users user = (Users) session.getAttribute("user");
		/** 判读用户是否登录 */
		if (user == null) {
			/** 当用户为空的时候，判读当前状态是否为想要去登录的状态，若是则允许到数据库中查询通过则登录 若不是返回到登录页面 */
			if ("login".equals(method)) {
				chain.doFilter(request, response);
			} else {
				httpResponse.sendRedirect("/login.jsp");
				return;
			}
		} else {
			/** 如果为超级管理员 */
			if (user.getIsUsersAdmin() == 1) {
				chain.doFilter(request, response);
			} else {
				chain.doFilter(request, response);
				// if (method != null) {
				// /** 检查不需要进行过滤的方法 若当前访问的在其中 那么 不拒绝 */
				// if (methodList.contains(method)) {
				// chain.doFilter(request, response);
				// /** 其它不允许访问的方法 1.要进行断定是否访问了栏目 */
				// } else {
				// /** 若访问的url中含有categoryId参数 那么要进行数据权限验证 即当前管理的栏目 */
				// String categoryId =
				// request.getParameter("categoryId");
				// if (!StringUtils.isEmpty(categoryId) &&
				// StringUtils.isNumeric(categoryId)) {
				// Long cid = Long.valueOf(categoryId);
				// Set<DataPermission> authSet =
				// user.getDataPermissionSet();
				// Set<Long> authIdSet = new HashSet<Long>();
				// for (DataPermission permission : authSet) {
				// if (!ObjectUtils.isNull(permission.getDataId()))
				// authIdSet.add(permission.getDataId().getCategoryId());
				// }
				// /** 如果权限集中有词栏目的id 那么允许通过 */
				// if (authSet.contains(cid)) {
				// chain.doFilter(request, response);
				// } else {
				// // TODO 提示信息
				// print("", httpResponse);
				// }
				// } else {
				/** 如果当期访问的url中没有categoryId这个参数 那么允许通过（即不检查栏目管理权限） */
				// chain.doFilter(request, response);
				// }
				// }
				// }
			}

		}

	}

	public void init(FilterConfig arg0) throws ServletException {
		this.filterConfig = arg0;

	}

	/**
	 * Allow subclasses to modify the redirection message.
	 * 
	 * @param request
	 *            the request
	 * @param response
	 *            the response
	 * @param url
	 *            the URL to redirect to
	 * @throws IOException
	 *             in the event of any failure
	 */
	protected void sendRedirect(HttpServletRequest request, HttpServletResponse response, String url) throws IOException {
		if (!url.startsWith("http://") && !url.startsWith("https://")) {
			url = request.getContextPath() + url;
		}
		System.out.println(url);
		response.sendRedirect(response.encodeRedirectURL(url));
	}

	private void print(String message, HttpServletResponse response) {
		try {
			response.setCharacterEncoding("UTF-8");
			response.setContentType("text/html;charset=utf-8");
			PrintWriter out = response.getWriter();
			out.print(message);
		}
		catch (IOException e) {
			e.printStackTrace();
		}

	}
}
